<?php

namespace app\lib\douyin;
use think\facade\Cache;
class douyin
{
    private  $Client_Key = "aw2rtr4o5egbkv54";
    private  $Client_Secret = "e4e5c33475c3bedcc26353333d377905";


    /**
     * 校验ticket
     */
    public function ticket(){
        $client_token = Cache::get('client_token');
        $ticket   =   Cache::get('ticket');
        if (empty($client_token)){
            $url = "https://open.douyin.com/oauth/client_token/";
            $data = [
                "client_key"=>$this->Client_Key,
                "client_secret"=>$this->Client_Secret,
                "grant_type"=>"client_credential"

            ];
            $res = $this->request_post($url,$data);
            $jsoninfo = json_decode($res, true);
            $client_token  =  $jsoninfo['data']['access_token'] ?? '';
            Cache::set('client_token', $client_token, 7200);//minutes
        }
        if (empty($ticket)){
            $url = "https://open.douyin.com/open/getticket/";
            $header[] = "Content-Type: application/json";
            $header[] = "access-token: ".$client_token;
            $res = $this->request_get($url,$header);
            $jsoninfo = json_decode($res, true);
            $ticket  =  $jsoninfo['data']['ticket'] ?? '';
            Cache::set('ticket', $ticket, 7200);//minutes
        }
        return $ticket;
    }


    /**
     * 生成签名
     */
    public function createSign($attributes){
        $string1 = $this->ASCII($attributes);
        $sign = md5($string1);
        return $sign;
    }


    public function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    /**
     * 追踪分享
     */
    public function share_id(){
        $client_token = Cache::get('client_token');
        $url = "https://open.douyin.com/share-id/?need_callback=true";
        $header[] = "Content-Type: application/json";
        $header[] = "access-token: ".$client_token;
        $res = $this->request_get($url,$header);
        $jsoninfo = json_decode($res, true);
        if ($jsoninfo['data']['error_code'] == 2190008){
            #access-token过期重新获取
            Cache::rm("ticket");
            Cache::rm("client_token");
            $this->ticket();
            $client_token = Cache::get('client_token');
        }
        $share_id  =  $jsoninfo['data']['share_id'] ?? '';
        return $share_id;
    }


    /**
     * 分享
     * share_type 写死为h5
     * client_key 应用key
     * nonce_str 随机字符串
     * timestamp 时间戳
     * signature 验签签名
     *
     */
    public function publishingContent($attributes,$Not_necessary = []){
        $baseUrl = "snssdk1128://openplatform/share?";
        $param = [
            "share_type"=>"h5",
            "client_key"=>$this->Client_Key,
            "nonce_str"=>$attributes["nonce_str"],
            "timestamp"=>$attributes["timestamp"],
            "signature"=>$attributes["signature"]
        ];
        $param = array_merge($param,$Not_necessary);
        $str = '';
        foreach ($param as $k=>$val){
            $str .= $k .'=' . $val . '&';
        }
        $strs = rtrim($str, '&');
        $baseUrl = $baseUrl.$strs;
        return $baseUrl;
    }


    /**
     * 获取access_token
     */
    public function getAccessToken($code = ''){
        $url = "https://open.douyin.com/oauth/access_token/";
        $data = [
            "client_secret"=>$this->Client_Secret,
            "code"=>$code,
            "grant_type"=>"authorization_code",
            "client_key"=>$this->Client_Key

        ];
        $res = $this->request_post($url,$data);
        $jsoninfo = json_decode($res, true);
        return $jsoninfo;
    }

    /**
     * 获取单独二维码授权
     */
    public function qrconnect(){
        $res = "https://open.douyin.com/qrconnect?client_key=".$this->Client_Key."&response_type=code&scope=user_info,video.data,video.list&jump_type=h5&redirect_uri=https://serve.youdnr.com/douyin/code";
        return $res;
    }

    private function ASCII($params = array()){
        if(!empty($params)){
            $p =  ksort($params);
            if($p){
                $str = '';
                foreach ($params as $k=>$val){
                    $str .= $k .'=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return $params;
    }

    /**
     * 发送get请求
     */
    private function request_get($url = '',$header = [])
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * 发送post请求
     */
    private function request_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }
}
